#include <xp/bas/sio.h>
#include <xp/bas/stdio.h>
#include <xp/bas/locale.h>
#include <xp/bas/errno.h>

int xp_main (int argc, xp_char_t* argv[])
{
	xp_sio_t src, tgt;
	xp_char_t buf[1000]; 
	xp_size_t err = 0;
	
	if (argc != 3) {
		//xp_printf (XP_TEXT("usage: %s source_file target_file\n"), argv[0]);
		xp_sio_putsn (xp_sio_out, 
			XP_TEXT("usage: "), argv[0], 
			XP_TEXT(" source_file target_file\n"), XP_NULL);
		return -1;
	}

	if (xp_setlocale () == -1) {
		//xp_printf (XP_TEXT("cannot setlocale\n"));
		xp_sio_puts (xp_sio_out, XP_TEXT("cannot setlocale\n"));
		return -1;
	}

	if (xp_sio_open (&src, argv[1], XP_TEXT("r")) == XP_NULL) {
		//xp_printf (XP_TEXT("cannot sio_open [%s]\n"), argv[1]);
		xp_sio_putsn (xp_sio_out, XP_TEXT("cannot sio_open ["),
			argv[1], XP_TEXT("]\n"), XP_NULL);
		return -1;
	}

	if (xp_sio_open (&tgt, argv[2], XP_TEXT("w")) == XP_NULL) {
		//xp_printf (XP_TEXT("cannot sio_open [%s]\n"), argv[2]);
		xp_sio_putsn (xp_sio_out, XP_TEXT("cannot sio_open ["),
			argv[2], XP_TEXT("]\n"), XP_NULL);
		return -1;
	}

	for (;;) {
		xp_ssize_t n = xp_sio_gets (&src, buf, xp_countof(buf));
		if (n == 0) break;

		if (n == -1) {
			if (xp_errno != XP_EILSEQ) break;

			err++;
			if (err > 10) break;
			continue;
		}

		xp_sio_puts (&tgt, buf);
	}

	if (err > 0) {
		xp_printf (XP_TEXT("=== %d sequence error(s) ===\n"), err);
	}

	xp_sio_close (&src);	
	xp_sio_close (&tgt);	
	return 0;
}


